package com.evil.DAO;

import com.evil.Bean.LocationBean;
import com.evil.DB_Utils.*;
import com.evil.DB_Utils.ErrorInfo;
import com.evil.Data.Data;
import com.google.gson.Gson;
import com.sun.xml.internal.bind.v2.runtime.Location;
import org.apache.log4j.Logger;

/********************************************
 * 工程名：Web
 * 包名：com.evil.DAO
 * 时间：16-9-19 下午8:46
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：记录用户位置DAO
 ********************************************/
public class LocationDAO
{
    private static Logger log = Logger.getLogger(LocationDAO.class);

    /**
     * 地址更新操作
     *
     * @param phone
     * @param bean
     */
    public void insertLocation(String phone, LocationBean bean)
    {
        String findUrl = "SELECT\n" +
                "location.location1,\n" +
                "location.location2,\n" +
                "location.location3\n" +
                "FROM\n" +
                "location\n" +
                "WHERE\n" +
                "location.phone = ?";


        DB_Utils.query(findUrl).add(phone).build().get(next ->
        {
            if (next.next())
            {
                String[] locations = new String[3];
                locations[0] = next.getString(2);
                locations[1] = next.getString(3);
                locations[2] = new Gson().toJson(bean);
                updateLocation(phone, locations);
            }
            else
            {
                updateLocation(phone, new String[]{"", "", ""});
            }
        }).close();
    }

    /**
     * 插入或者更新
     */
    private void updateLocation(String phone, String[] locations)
    {
        String replaceUrl = "REPLACE `edasupport`.`location` SET `phone`=?, `location1`=?, `location2`=?, `location3`=?;";
        String re = DB_Utils.update(replaceUrl)
                .add(phone)
                .add(locations[0])
                .add(locations[1])
                .add(locations[2])
                .build().close();
        if (re.equals(ErrorInfo.ERROR_NO_FOREIGN_VALUE.toString()))
            log.error(phone + "发生严重崩溃错误，位置:" + LocationDAO.class.getName()+"\r\n");
    }

}
